package com.juma.cartridge.mqbox;

import java.io.IOException;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.AbstractMessageConverter;
import org.springframework.amqp.support.converter.MessageConversionException;

import com.juma.cartridge.common.HessianIOUtils;

/**
 * hessian消息序列化转换器
 * @ClassName HessianMessageConverter
 * @Description
 * @Author zhuangguangyou
 * @Date 2019年11月15日 下午5:18:17
 * @Version 1.0
 *
 */
public class HessianMessageConverter extends AbstractMessageConverter {

    @Override
    protected Message createMessage(Object object, MessageProperties messageProperties) {
        if(object instanceof Message) {
            return (Message)object;
        }
        
        byte[] data;
        if(object instanceof byte[]) {
            data = (byte[])object;
        } else {
            try {
                data = HessianIOUtils.serialize(object);    
            }catch(IOException e) {
                throw new RuntimeException("hessain序列化失败",e);
            }
        }
        messageProperties.setContentType(MQContentType.hessian.name());
        messageProperties.setContentLength(data.length);
        Message msg = new Message(data,messageProperties);
        return msg;
    }

    @Override
    public Object fromMessage(Message message) throws MessageConversionException {
        String ctype = message.getMessageProperties().getContentType();
        try {
            MQContentType incomeType = MQContentType.valueOf(ctype);
            if(incomeType!=MQContentType.hessian) {
                throw new MessageConversionException("消息非hessian序列化类型==>contentType:"+ctype);
            }
            return HessianIOUtils.deserialize(message.getBody());
        }catch(IOException ioe) {
            throw new MessageConversionException("消息反序列化失败",ioe);
        }catch(IllegalArgumentException re) {
            throw new MessageConversionException("消息非hessian序列化类型==>contentType:"+ctype);
        }
        
    }
}
